import {TouchableOpacity, View, processColor} from 'react-native';
import {Text, useAppTheme} from 'tsun-smart-ui';
import {useLayoutEffect, useMemo} from 'react';
import Orientation from 'react-native-orientation-locker';
import Segmented from '../Segmented';
import {unitMap} from '@/enums/statistics';
import {useTranslation} from 'react-i18next';
import {DatePickerStep, dataMap} from '@/pages/scene/Owner/statistics';
import useDatePicker from '@/hooks/useDatePicker';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import MemoBarChart from '../BarChart';
import LineChart from '../LineChart';
import {HeaderBackButton} from '@react-navigation/elements';
import {hexWithOpacity} from '@/utils';
import {useNavigation} from '@react-navigation/native';
// 新增：引入redux
import {useSelector, useDispatch} from 'react-redux';
import {RootState} from '@/store';
import {
  toggleColorVisible,
  setSelected,
  colors as colorsList,
  setColors,
} from '@/store/slices/landscapeColorsSlice';
import {withCancelable} from '@/utils';
import {deviceApi} from '@/services/api/deviceApi';
import {useGetNaviTheme} from '@/hooks/useTheme';
import { useStatusBarHidden } from '@/hooks/useStatusBarHidden';
export type DatePickerStepType = keyof typeof unitMap;
const queryGenEle = withCancelable(deviceApi.getStationStatistics);

export default function Landscape({
  route: {
    params: {stationId},
  },
}: ReactNavigation.RootStackScreenProps<'FullScreen'>) {
  const theme = useAppTheme();
  const {t} = useTranslation();
  const currentStation = useSelector(
    (state: RootState) => state.fullScene.currentStation,
  );
  const options = Object.entries(unitMap).map(([key, value]) => ({
    label: t(value),
    value: key as DatePickerStepType,
  }));
  // 用redux管理colors和selected
  const colors = useSelector(
    (state: RootState) => state.landscapeColors.colors,
  );
  const selected = useSelector(
    (state: RootState) => state.landscapeColors.selected,
  );
  const dispatch = useDispatch();
  const {left, right, bottom, top} = useSafeAreaInsets();
  useLayoutEffect(() => {
    Orientation.lockToLandscapeLeft();
    return () => {
      Orientation.lockToPortrait();
    };
  }, []);
  useStatusBarHidden()
  const params = useMemo(() => {
    return {
      stationId: stationId || currentStation?.id,
    };
  }, [currentStation]);
  const {
    Picker: picker,
    selectedValue: value,
    setSelectedValue: setValue,
    result,
    currentUnit,
  } = useDatePicker(selected, queryGenEle, params);
  const chartData = useMemo(() => {
    const {viewData, ...totalData} = result ?? {};
    const originData = Object.entries(totalData);
    const xAxisLabels = originData[0]?.[1]?.map(item => item.time) ?? [];
    const values = originData.map(([_, value]) =>
      (value ?? []).map(item => +item.value),
    );
    return {
      xAxisLabels,
      values,
    };
  }, [result]);
  useLayoutEffect(() => {
    const {viewData = {}} = result ?? {};
    const data = Object.entries(viewData);
    const colors = data.map(([title], index) => {
      return {
        title: t(
          dataMap[title as keyof typeof dataMap].legend[
            selected === 'day' ? 'day' : 'total'
          ],
        ),
        color: colorsList[index],
        visible: true,
      };
    });
    dispatch(setColors(colors));
  }, [result, selected]);
  const naviTheme = useGetNaviTheme();
  const navigation = useNavigation();
  return (
    <View
      className="flex-1"
      style={{
        backgroundColor: theme.colors?.neutral?.white,
        paddingLeft: left + 32,
        paddingRight: right + 32,
        paddingBottom: bottom,
        paddingTop: top,
      }}>
      <HeaderBackButton
        onPress={() => {
          navigation.goBack();
        }}
        style={{position: 'absolute', left: 48, top: 16 + top}}
        tintColor={naviTheme.colors.text}
      />
      <View className="mt-4 w-[303] self-center">
        <Segmented
          className="min-w-48"
          buttons={options}
          value={selected}
          onChange={v => dispatch(setSelected(v))}
        />
      </View>
      <DatePickerStep
        disabled={currentUnit === 'total'}
        type={currentUnit}
        value={value}
        setValue={setValue}
        onPress={() => {
          picker.show();
        }}></DatePickerStep>
      <View className="flex-1">
        {currentUnit === 'day' ? (
          <LineChart
            showFullScreen={false}
            leftUnit={`${t('device.power')}(kW)`}
            rightUnit={`SOC(%)`}
            yAxis={{
              left: {
                drawAxisLine: true,
              },
              right: {
                enabled: true,
                drawGridLines: false,
                drawAxisLine: true,
              },
            }}
            style={{
              flex: 1,
            }}
            scaleYEnabled={false}
            showLegend={false}
            dataSetsConfig={colors.map(item => {
              const currentColor = processColor(item.color);
              return {
                color: currentColor,
                drawValues: false,
                drawCircles: false,
                fillGradient: {
                  colors: [
                    processColor(hexWithOpacity(item.color, 0)),
                    processColor(hexWithOpacity(item.color, 0.4)),
                  ],
                  orientation: 'BOTTOM_TOP',
                },
                visible: item.visible ?? true,
                fillAlpha: 100,
              };
            })}
            title={colors.map(item => item.title)}
            marker={`${t('sys.app.time')}: `}
            xAxisLabels={chartData.xAxisLabels}
            chartData={chartData.values}
            highlightPerTapEnabled={colors.some(item => item.visible)}
          />
        ) : (
          <MemoBarChart
            showFullScreen={false}
            leftUnit={`${t('device.electricity_production')}(kWh)`}
            xAxis={{
              centerAxisLabels: colors.length > 1,
            }}
            yAxis={{
              right: {
                enabled: false,
              },
            }}
            style={{
              flex: 1,
            }}
            scaleYEnabled={false}
            showLegend={false}
            dataSetsConfig={colors.map(item => {
              const currentColor = processColor(item.color);
              return {
                color: currentColor,
                drawValues: false,
                visible: item.visible ?? true,
                fillAlpha: 100,
              };
            })}
            title={colors.map(item => item.title)}
            marker={`${t('sys.app.time')}: `}
            xAxisLabels={chartData.xAxisLabels}
            chartData={chartData.values}
            highlightPerTapEnabled={colors.some(item => item.visible)}
          />
        )}
      </View>
      <View className="flex-row flex-wrap gap-y-2 gap-x-3 mt-5">
        {colors.map(color => {
          return (
            <TouchableOpacity
              key={color.title}
              onPress={() => {
                dispatch(toggleColorVisible(color.title));
              }}
              style={{
                borderColor: !color.visible
                  ? theme.colors?.background?.disabled
                  : theme.colors?.background?.primary,
                backgroundColor: !color.visible
                  ? theme.colors?.neutral?.white
                  : theme.colors?.background?.primary,
              }}
              className="flex-row items-center gap-x-1 py-[6] px-[10]  border rounded-2xl">
              <View
                className=" size-2 rounded-full"
                style={{
                  backgroundColor: color.color,
                }}></View>
              <Text
                variant="caption"
                style={{
                  color: theme.colors?.neutral?.primary,
                }}>
                {color.title}
              </Text>
            </TouchableOpacity>
          );
        })}
      </View>
    </View>
  );
}
